package com.chif.goingplus.websocket;

import com.alibaba.fastjson.JSON;
import com.chif.goingplus.pojo.Message;
import com.chif.goingplus.utils.CharServiceUtils;
import com.chif.goingplus.utils.JsonUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 相当于后端请求的websocket连接端口，之后调用sendTextMessage方法向前端发送数据
 */
@CrossOrigin
@Component
@ServerEndpoint("/websocket/{chartId}")
//此注解相当于设置访问URL
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="chartId")String chartId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(chartId, session);
        System.out.println(sessionPool.toString());//测试会话池
        System.out.println("【websocket消息】有新的连接，总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开，总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
        Message msg = JSON.parseObject(message, Message.class);
        switch (msg.getAction()){
            case "getData":
                msg.setValue(CharServiceUtils.getchartData(msg.getChartName()));
                sendAllMessage(JsonUtils.getJson(msg));
                break;
            case "fullScreen":
                msg.setValue(CharServiceUtils.getchartData("count"));
                sendAllMessage(JsonUtils.getJson(msg));
                System.out.println(msg);
                break;
            case "themeChange":break;
        }
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息 (发送文本)
    public void sendTextMessage(String chartId, String message) {
        Session session = sessionPool.get(chartId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息 (发送对象)
    public void sendObjMessage(String chartId, Object message) {
        Session session = sessionPool.get(chartId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendObject(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

